<template>
    <div style="height:100%;">
        <div v-transfer-dom>
            <loading v-model="isLoading" :text ="loadingText"></loading>
        </div>
        <view-box ref="viewBox" :body-padding-top="headerH" :body-padding-bottom="navH">
            <x-header slot="header" style="width:100%;position:absolute;left:0;top:0;z-index:601;" :title="showWxappBack?'<返回功能演示':title" :left-options="{showBack:!showWxappBack}" :transition="headerTransition" v-show="isHeadShowB" @click.native="showBackGif"></x-header>
            <transition :name="mainTrans?('vux-pop-' + (direction === 'forward' ? 'in' : 'out')):'in'">
                <keep-alive>
                    <router-view class="router-view"></router-view>
                </keep-alive>
            </transition>
            <tabbar id="menus" class="vux-demo-tabbar" v-show="isNavShow" icon-class="vux-center" slot="bottom">
                <tabbar-item @on-item-click="onBtnTask" :selected="$route.path.indexOf('/m_task')==0">
                    <span v-show="$route.path.indexOf('/m_task')!=0" slot="icon" class="iconfont icon-renwu"></span>
                    <span v-show="$route.path.indexOf('/m_task')==0" style="font-size: 30px;" @click.native="" slot="icon" class="iconfont icon-tianjia1"></span>
                    <span v-show="$route.path.indexOf('/m_task')!=0" slot="label">日程</span>
                </tabbar-item>
                <tabbar-item @on-item-click="golink('/m_timeauto')" :selected="$route.path.indexOf('/m_timeauto')==0">
                    <span slot="icon" class="iconfont icon-icon-yxj-life1"></span>
                    <span slot="label">助手</span>
                </tabbar-item>
                <!--  @on-item-click="$vux.toast.show({text:'暂未开放',type: 'warn'})"  disabled  -->
                <tabbar-item  @on-item-click="golink('/m_market')" :selected="$route.path === '/m_market'">
                    <span slot="icon" class="iconfont icon-tubiaozhizuomoban"></span>
                    <span slot="label">筛选</span>
                </tabbar-item>
                <tabbar-item @on-item-click="golink('/m_mine')" :selected="$route.path === '/m_mine'">
                    <span slot="icon" class="iconfont icon-zhaopin1"></span>
                    <span slot="label">我的</span>
                </tabbar-item>
            </tabbar>
        </view-box>
        <task-add :show="showTaskAdd" :ext="addTaskExt" v-on:toVisible="taskAddVis"></task-add>
        </div>
    </div>
</template>
<script>
import util from './data/util'
import moment from "moment";
import {
    Toast,ButtonTab,ButtonTabItem,ViewBox,XHeader,Tabbar,TabbarItem,Loading,Actionsheet,TransferDom
} from 'vux'

import Vue from 'vue'
import {
    mapState,
    mapActions
} from 'vuex'


import { taskAndTag } from "./components/mixin";
import { help } from "./components/mixinApp";
import api from './api'
import TaskAdd from "./components/TaskAdd";

let pageIndex = {
    "/": 1,
    "/index": 1,
    "/m_jobs": 2,
    "/m_companys": 3,
    "/m_news": 4,
    "/m_mine": 5
};
let lastPos = 0;
let lastPath = "/";
let pre_main = "/m_";
let pre_NONE = "/n_"; //n 不显示header nav 的页面.

export default {
    directives: {
        TransferDom
    },
    components: {
        Toast,ButtonTab,ButtonTabItem,ViewBox,XHeader,Tabbar,TabbarItem,Loading,Actionsheet,TaskAdd
    },
    mixins: [taskAndTag,help],
    computed: {
        ...mapState({
            route: state => state.route,
            path: state => state.route.path,
            deviceready: state => state.app.deviceready,
            demoTop: state => state.vux.demoScrollTop,
            isLoading: state => state.vux.isLoading,
            loadingText: state => state.vux.loadingText,
            direction: state => state.vux.direction,
            isHeadShow: state => state.vux.isHeadShow,
            isNavShow: state => state.vux.isNavShow,
            uid: state => state.vux.uid,
            title: state => state.vux.title,
            addTaskExt: state => state.z39.addTaskExt,
            addTaskShow: state => state.z39.addTaskShow,
            taskDic: state => state.z39.taskDic,
        }),
        isHeadShowB() {
            var isMainPage = false;
            var path = this.$route.path;
            var tempHeadShow = false;
            if(path=="/") return;//解决闪屏,首页进入系统后router设置会自动跳转
            var isnone = this.is_none(path);
            if (isnone) {
                this.headerH = "0";
                this.navH = "0";
            } else {
                isMainPage = this.is_main(path);
                var ua = navigator.userAgent.toLowerCase();
                // this.isHeadShow = !isMainPage;
                // this.$store.commit("isHeadShow", {value:!isMainPage});
                tempHeadShow = !isMainPage ;
                var isWx = this.is_weixin();
                var isWb = this.is_weibo();
                var isWxApp = window.__wxjs_environment === 'miniprogram';
                if (isWxApp && !Vue.device.isAndroid) {
                    this.showGif = this.showGif||parseInt(localStorage.getItem("showGif"))||0;
                    var val = tempHeadShow && isWxApp && this.showGif < 103 ;
                    if(!val && this.showWxappBack){
                        var gifval = this.showGif < 100?100:this.showGif++ ; //显示2次,避免用户第一次后还不会使用
                        localStorage.setItem("showGif", gifval);
                    }
                    console.log("---showGif:",this.showGif,this.showWxappBack,val,tempHeadShow);
                    this.showWxappBack = val;
                    tempHeadShow = val ;
                }else if(isWx ||isWb){
                    tempHeadShow = false;
                }
                var tempNavShow = isMainPage ;
                this.headerH = tempHeadShow ? "46px" : "0";
                this.navH = tempNavShow ? "55px" : "0";
                // console.log("headshow:" + this.isNavShow + this.isHeadShow);
            }
            this.$store.commit("isHeadShow", {value:tempHeadShow});
            this.$store.commit("isNavShow", {value:isMainPage});
            return tempHeadShow;
        },
        headerTransition() {
            return this.direction === 'forward' ? 'vux-header-fade-in-right' : 'vux-header-fade-in-left'
        }
    },
    mounted: function() {
      util.calc()
        // console.log("app mounted ready！");
        // this.isHeadShowC();
        // this.showHeadC();
        this.checkLogin().then(data=>{
			this.checkInvite();
            this.usertask();
        },data=>{
            this.checkInvite();
			console.log("this.parseDefault");
			this.parseDefault();
		}) ;
        this.showVersion();
        this.changeTitle();
                    
        var param = this.GetRequest();
        let _this = this ;
        // if (param.h5 != undefined && param.action == undefined) {
        //   var temp = decodeURIComponent(param.h5) ;
        //   var content = "点击确定进入" + (param.type=="wxtmp"?"任务详情":"分享链接");
        //   this.$vux.confirm.show({
        //     title: "进入子页面",
        //     content: content,
        //     onCancel() {},
        //     onConfirm() {
        //       _this.$router.push(temp);
        //     }
        //   })
        //   mode = 2;
        //   // console.error("param:", temp);
        // }
        var tp = window.location.href ;
        var index = tp.indexOf("#") ;
        tp = tp.substr(index+1);
        index = tp.indexOf("?") ;
        if(index!=-1) tp = tp.substr(0,index);        		
        // console.log("version:",this.version.ver,this.$route.path,tp,window.location.href);
    },
    created() {
        // if (userInfo && userInfo.uid) { // userInfo 是index.html中的js对象; 有了api中自赋值token,和程序本身的login协议
        //     this.user(userInfo);
        //     this.login(true);
        // }
        this.$vux && this.$vux.bus && this.$vux.bus.$on('routeSet', this.doRouteChange);
		this.$vux.bus.$on('taskAddVisible', this.taskAddVisible);
        if(isApp){
            plus.runtime.setBadgeNumber(0);
            if(mui.os.ios){
                var GeTuiSdk = plus.ios.importClass('GeTuiSdk');
                GeTuiSdk.setBadge(0);
            }
        }
    },
    watch: {
        "$route": function() {
            this.changeTitle();
        },
    },
    sockets:{  //事件监听
        connect: function(){
          if( this.$socket.id == null ) return ;
          this.$store.commit("sid", {sid:this.$socket.id});
          console.log("sockets connect in",this.$socket.id);

          setTimeout(()=>{
            if(!this.wsLogin && this.uid && api.token) this.$socket.emit('wsLogin', JSON.stringify({uid:this.uid,token:api.token}) );
          },200)
        },
        error:function(e){
            // console.log("socket error",e);
        },
        taskNumUpdate:function(val){
            if(!this.socketOpen) return ;
            let data = JSON.parse(val) ;
            let curr = data.curr ;
            let total = data.total ;
            // const h = this.$createElement; //`任务数:${curr}/${total}`
            // this.$message({
            //   title: '进度',
            //   message: `任务数:${curr}/${total}`,
            //   type: 'info'
            // });
            // console.log("taskNumUpdate",data);
        },
        tasklistUpdate: function(val){
          if(!this.socketOpen) return ;
          let task ,tasks;
          try{
            task = JSON.parse(val) ;
            tasks = task instanceof Array ? task : [task] ;
            this.$store.commit({ type: "z39/taskToDB", tasks: tasks, act: "add" });

            console.log('server tasklistUpdate:',tasks.length);
          }catch(e){
            // console.log("error:",e) ;
          }
         // console.log('server tasklistUpdate:');
         // console.log('server tasklistUpdate:',val);
        },
        async taskUpdate(val){
          if(!this.socketOpen) return ;
          let task;
          try{
            task = JSON.parse(val) ;
            var title =task.title ;
            var dayi,daym,time,day,temp,postfix,daymo,need,h,m;
            var timeReg = /^(今天晚上|明天早上|明天晚上|明天下午|后天早上|后天下午|后天晚上|今天|明天|后天|明早|明晚|今晚|晚上|下午)?((\d{1,2}|零|一|二|三|四|五|六|七|八|九|十|十一|十二|十三|十四|十五|十六|十七|十八|十九|二十|二十一|二十二|二十三|二十四)(点半|点|:)([零|一|二|三|四|五|六|七|八|九|十]{0,3}|\d{0,2})(分钟|分))/;
            var needReg = /^评估(\d{1,2}|[零|一|二|三|四|五|六|七|八|九|十]{1,2})个?小时(([零|一|二|三|四|五|六|七|八|九|十]{1,3}|\d{1,2})分?钟?)?|^评估(([零|一|二|三|四|五|六|七|八|九|十]{1,3}|\d{1,2})分钟)/;
            var tm = title.match(timeReg);
            var nr = title.match(needReg);
            if(nr){ //如果满足评估条件,则不满足闹钟规则.
                postfix =title.substr(nr[0].length);
                need = this.getNeedbyReg(nr);
                this.setAutoNeed(task,need,postfix);
            }else if(tm){
                postfix =title.substr(tm[0].length);
                time = this.getDueDay(tm,task);
                await this.setAutoDue(task,time,postfix);
                nr = postfix.match(needReg);
                if(nr){ 
                    postfix =postfix.substr(nr[0].length);
                    need = this.getNeedbyReg(nr);
                    this.setAutoNeed(task,need,postfix);
                }
            }else this.$store.commit(Object.assign({ type: "z39/taskSet" }, task, { task:true }));
          }catch(e){ console.error("error",e)}
        },
        tagUpdate: function(val){
          if(!this.socketOpen) return ;
          try{
            let tag = JSON.parse(val) ;
            this.$store.commit({ type: "z39/tagUpdate", tag: tag });
            bus.$emit('tagUpdate');
            this.$vux && this.$vux.bus && this.$vux.bus.$on('tagUpdate');
            console.log('server tagUpdate:',tag);
          }catch(e){}
        },
        wsloginResult: function(val){
          let data = JSON.parse(val) ;
          if( data.errno >0) this.$store.commit("wsLogin", {wsLogin:true});
          console.log('wslogin登录结果:',data);
        },
        taskWarn: function(val){  //任务超时提醒,任务开始提醒.
          let data = JSON.parse(val) ;
          let msg = {title: '任务提示',message: '',type:"info",duration:3000};
          msg = Object.assign(msg,data);
          this.$vux.toast.text(msg.message);
          // this.$notify(msg);
          // console.log("task:",data);
        },
		clock:function(val){
			let data = JSON.parse(val) ;
			let time = data.phase == 1 ? 10:0 ;
			this.$vux.clock.show({
			  cancelText:"关闭",
			  delayText:"延迟",
			  title:"闹钟",
			  content: "任务:"+(data.title || "时间清单"),
			  showDelay:false,
			  autoClose:time,
			  onCancel () {
				console.log("close") // 当前 vm
			  },
			  onDelay () {
				console.log("dalay")
			  }
			})
			console.log("clock",data);
		},
        msgSys: function(val){

          console.log('系统消息:',val);
        }
    },
    methods: {
        async setAutoDue(task,time,ntitle){
            // var time = match[0];
            let due = time.length>10?time:(moment().format("YYYY-MM-DD ")+time);
            var id = task.id;
            var sdata = {taskid:id,key:"due",value:due,ignore:1};
            var item = this.taskDic[id] ; //store.taskdic中获取.
            let data = await this.doTagSet(item,"due",due);
            let tdata = {id,title:ntitle,ignore:1};
            data = await api.taskSet(tdata)
            if (data == undefined || data.errno != 0) return;
            delete tdata.ignore;
            this.$store.commit(Object.assign({ type: "z39/taskSet" }, tdata, { task: item }));
        },
        async setAutoNeed(task,need,ntitle){
            var id = task.id;
            var item = this.taskDic[id] ;
            let data = await this.doTagSet(item,"need",need);
            let tdata = {id,title:ntitle,ignore:1};
            data = await api.taskSet(tdata)
            if (data == undefined || data.errno != 0) return;
            delete tdata.ignore;
            this.$store.commit(Object.assign({ type: "z39/taskSet" }, tdata, { task: item }));
        },
        getNeedbyReg(nr){ //把匹配到的正则表达式字符转换成评估时间（单位秒）
            var h,m,need;
            h = nr[1],m = nr[3];
            if(!h && !m){
                h = 0,m= nr[6];
            }
            h = this.ChineseToNumber(h);
            m = this.ChineseToNumber(m);
            need = parseInt(h)*3600 + parseInt(m)*60;
            return need ;
        },
        getDueDay(tm,task){ //把文字中匹配到的日期文字转换成日期格式
            var dayi,daym,time,day,temp,postfix,daymo,need,h,m;
            daym = tm[1],time = tm[2];
            if(daym&&daym.indexOf("今")!=-1) dayi=0;
            else if(daym&&daym.indexOf("明")!=-1) dayi=1;
            else if(daym&&daym.indexOf("后")!=-1) dayi=2;
            else console.log("没有前置日期,今天,明天,后台");
            time = time.replace("点半",":30").replace("点",":").replace("分钟","").replace("分","");
            temp = time.split(":");
            temp[0] = this.ChineseToNumber(temp[0]);
            temp[1] = this.ChineseToNumber(temp[1]);
            if(temp.length==1) temp.push("00"); //9点->9:00
            if(daym&& ( daym.indexOf("下午")!=-1 || daym.indexOf("晚")!=-1) && parseInt(temp[0])<=12) temp[0] = 12 + parseInt(temp[0]) +"";
            temp[1] = temp[1] ||"00"; //解决'晚上8点',没有分钟
            temp[0] = temp[0].length>1?temp[0]:("0"+temp[0]);
            temp[1] = temp[1].length>1?temp[1]:("0"+temp[1]);
            if(temp[0]>=24) temp[0] = "00", dayi++; //24点
            time = temp.join(":");
            var item = this.taskDic[task.id] ;
            if(item.tags && item.tags.due && item.tags.due.length>=10) daymo = moment(item.tags.due.substr(0,10));
            else daymo = moment();
            day = daymo.add("d",dayi).format("YYYY-MM-DD ");
            return day + time ;
        },
        onClickMore() {
            this.showMenu = true
        },
        golink(link){
            link = localStorage.getItem(link) || link ;
            this.$router.push(link);
        },
        checkLogin() { //token登录
            let _this = this;
            var token = window.localStorage.getItem('token');
            var guestToken = window.localStorage.getItem('guestToken');
            if(token && token != guestToken)  window.localStorage.setItem('guestToken',"");
            token = token || guestToken ;
            if (token) {
                return api.loginToken({token}).then(data => {
                    if (data && data.errno == 0) {
                        data = data.data;
						_this.$store.commit(Object.assign({ type: "user" }, data));
                        // this.importDefault();   //导入展示数据.
                        return Promise.resolve(data);
                    } else {
						return Promise.reject({errno:1001,msg:'no token'});
					}
                })
            }else if( guestToken == null ){
                let sdata = {} ;
                return api.guestRegist(sdata).then(data => {
                    if (data && data.errno == 0) {
                        data = data.data;
                        _this.$store.commit(Object.assign({ type: "user" }, data));
                        // this.importDefault();   //导入展示数据.
                        return Promise.resolve(data);
                    } else {
                        return Promise.reject({errno:1001,msg:'no token'});
                    }
                })
            }else{
                return Promise.reject({errno:1001,msg:'no token'});
            }
        },
        changeTitle() {
            let t = this.app.title;
            if (this.$route.name) {
                t = this.$route.name;
            }
            // this.title = t;
            this.$store.commit({ type: "title" ,title:t } );
            this.setTitle(t);
        },
        doRouteChange(val){
            console.log("doRouteChange:",val);
            this.go(val);
        },
        changeLocale(locale) {

        },
        is_main(path) {
            if (path.length > 2 && path.indexOf(pre_main) < 0) {
                return false;
            }
            return true;
        },
        is_none(path) {
            if (path.length > 2 && path.indexOf(pre_NONE) >= 0) {
                return true;
            }
            return false;
        },
        showBackGif(){
            if(this.showWxappBack)this.$vux.slidegif.show();
        },
        taskAddVis(val){
            this.showTaskAdd = val ;
        },
        onBtnTask(){
            if(this.$route.path.indexOf('/m_task')==0){
                return this.showTaskAdd=true ;
            }
            var path = "m_task" ;
            var visit = localStorage.getItem("/" + path);
            if ( visit !=undefined) path = visit.replace(/^\//,"");
            this.go(path);
        },
        onBtnAuto(){
            if(this.$route.path=='/m_timeauto/habit'){
                return this.showTaskAdd=true ;
            }
            var path = "m_timeauto" ;
            var visit = localStorage.getItem("/" + path);
            if ( visit !=undefined) path = visit.replace(/^\//,"");
            this.go(path);
        },
        ChineseToNumber:function (chnStr){
            if(!chnStr) return 0 ;
            if(!isNaN(chnStr)) return chnStr ;
            chnStr += "" ; //转换成字符
            var chnNumChar = {零:0,一:1,二:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9};
            var str,res = "" ;
            if(chnStr.length==3) str = chnStr.replace("十",""); //二十一
            else if(chnStr.length==2){
                if(chnStr.substr(0,1)=="十") str = chnStr.replace("十","1"); //是十一
                else str = chnStr.replace("十","0"); //是五十
            } 

            for(var i = 0; i < str.length; i++){
                var num = chnNumChar[str[i]];
                if(typeof num !== 'undefined') res+= num ;
                else res+= str[i] ;
            }
            return res;
        },
        taskAddVisible:function(value){
            this.showTaskAdd=value ;
        },
        ...mapActions([
            'user', 'amount', 'headimg', 'login',
        ])
    },
    data() {
        return {
            // title: "7dtime",
            showMenu: false,
            // isHeadShow: false,
            // isNavShow: true,
            headerH: '0',
            navH: '55px',
            mainTrans: false,
            showWxappBack:false,
            showGif:"",
            showTaskAdd:false,
        }
    }
}
</script>
<style lang="less">
@import '~vux/src/styles/reset.less';
@import '~vux/src/styles/1px.less';
@import '~vux/src/styles/tap.less';
body {
    background-color: #fbf9fe;
}

html,
body {
    height: 100%;
    width: 100%;
    overflow-x: hidden;
}
sup{
    position: absolute;
    top: -8px;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    z-index: 101;
}
#vux_view_box_body .weui-cells {
    margin-top: 8px;
}

#menus .iconfont {
    font-size: 22px;
}

#vux_view_box_body {
    background-color: #f0f0f0;
}

.vux-pop-out-enter-active,
.vux-pop-out-leave-active,
.vux-pop-in-enter-active,
.vux-pop-in-leave-active {
    will-change: transform;
    transition: all 500ms;
    height: 100%;
    width: 100%;
    position: absolute;
    backface-visibility: hidden;
    perspective: 1000;
}

.vux-pop-out-enter {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
}

.vux-pop-out-leave-active {
    opacity: 0;
    transform: translate3d(100%, 0, 0);
}

.vux-pop-in-enter {
    opacity: 0;
    transform: translate3d(100%, 0, 0);
}

.vux-pop-in-leave-active {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
}

.in-enter-active {
    opacity: 1
}

.in-enter,
.in-leave-active {
    opacity: 0
}

#type .weui-search-bar {
    z-index: 600;
}

#type .vux-tab .vux-tab-item {
    line-height: 35px;
}

#type .vux-tab {
    height: 35px;
}
.p_task .weui-cell label,.p_task .weui-cell span{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.p_task .weui-cell label{
  -webkit-line-clamp: 1;
}
.p_task .weui-cell span{
  -webkit-line-clamp: 2;
}
.p_task .taskAdd{width:50px;height:50px;position:absolute;right:10px;bottom:62px;border-radius: 25px;z-index:2;}

.p_task .weui-cell .weui-cell__hd{max-height: 50px;}
.p_task .weui-cell{padding: 10px}
.p_task .weui-cells {
    margin-top: 0px;
}
.p_task .weui-cell img {
    /*max-width: 100px;
    width: auto;*/
    height: 50px;
    width: 50px;
    margin-right: 10px;
}
.p_task .task_done p{
    text-decoration:line-through;
}
.p_task .task_cancle{
    text-decoration:line-through;
    color: #b0b6bb;
}
.p_task .task_going{
    color: #10aeff;
}
.p_task .task_toggle{
    color: #e64340;
}
.p_task .task_curr .weui-cell{
    border-left: 5px solid #10aeff;
    border-radius: 4px;
    padding-left: 5px;
}
.p_task .task_curr .taskCount,.p_task .task_done .taskCount,.p_task .task_cancle .taskCount,.p_task .task_going .taskCount,.p_task .task_toggle .taskCount{color: #000000;}
#p_task .weui-cells {
    margin-top: 0px;
}

#p_task .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
/*#p_task .vux-tab .vux-tab-item{
    background: #fff;
}*/
#p_task .day  .vux-tab-selected {
    background: #eee;
    border-radius: 4px;
}

#p_task .vux-label-desc{
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-all;
}
#p_task .vux-label,#p_task .tTitle{
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-all;
}
.p_task .weui-cell .weui-cell__hd .taskCount{
    position:absolute;bottom:10px;left:10px;width: 50px;text-align: center;border-radius: 0 0 8px 8px;background-color: #10aeff87;height:14px; overflow:hidden;font-size: 12px;
}

.p_task .task_curr .weui-cell .weui-cell__hd .taskCount{
    left: 5px;
}
.flagshow{
 display:flex;
 height:30px;
 overflow:scroll;-webkit-overflow-scrolling:touch;background-color:#fff;
 width: 100%;
}
.flagshow span{
    height: 30px;
    line-height: 30px;
    background-position: right center;
    background-image: url(/static/z39h5/images/arrowR.png);
    padding: 0 15px 0 15px;
    background-repeat: no-repeat;
    background-size: contain;
    min-width: 60px;
    /*background-color: #c2eaff;*/
}
#vux_view_box_body .group0 .weui-cells{
    margin-top:0;
}
</style>
